package com.grape.transaction.tcc.producer.service;

import com.codingapi.txlcn.tc.annotation.DTXPropagation;
import com.codingapi.txlcn.tc.annotation.TccTransaction;
import com.codingapi.txlcn.tc.annotation.TxTransaction;
import com.codingapi.txlcn.tracing.TracingContext;
import com.google.common.collect.Sets;
import com.grape.transaction.tcc.producer.entity.User;
import com.grape.transaction.tcc.producer.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class ProducerService {
    private ConcurrentHashMap<String, Set<Integer>> ids = new ConcurrentHashMap<>();
    @Autowired
    UserMapper userMapper;

    @TccTransaction(propagation = DTXPropagation.SUPPORTS,confirmMethod = "confirmRpc",cancelMethod = "cancelRpc")
    @Transactional
    public void addUser(String i) {
        int line = userMapper.insert("myx2", 28);
        ids.putIfAbsent(TracingContext.tracing().groupId(), Sets.newHashSet(line));
        ids.get(TracingContext.tracing().groupId()).add(line);
    }

    public void confirmRpc(String value) {
        ids.get(TracingContext.tracing().groupId()).forEach(id -> {
            log.info("tcc-confirm-{}-{}" + TracingContext.tracing().groupId(), id);
            ids.get(TracingContext.tracing().groupId()).remove(id);
        });
    }

    public void cancelRpc(String value) {
        ids.get(TracingContext.tracing().groupId()).forEach(id -> {
            log.info("tcc-cancel-{}-{}", TracingContext.tracing().groupId(), id);
            log.info("删除数据");
        });
    }
}
